// pages/address/address.js

import api from "../../utils/api.js";
import message from "../../utils/message.js";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    addressList:[],
    hasLoad:false,
    type:'base',
    tab_index:0,
    shop_address_list:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    if(options.type){
      this.setData({
        type:options.type
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var me = this;
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    message.show_loading();
    api.getAddressList((resp) => {
      message.hide_loading();

      if( resp.status==1 ){

        this.setData({
          addressList: resp.data,
          hasLoad: true
        })
      }else{
        message.show_error( response.message );
      }
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  getAddressList:function(){
    api.getAddressList((resp) => {
      console.log(resp);
      if( resp.status==1 ){
        this.setData({
          addressList: resp.data,
          hasLoad: true
        })
      }
    })
  },

  getShopAddressList:function(){

  },

  useAddress:function( e ){
    var index = e.currentTarget.dataset.index;

    var address = this.data.addressList[index];

    var pages = getCurrentPages();
    var length = pages.length;

    //加载上一页
    var prev_page = pages[ length-2];

    prev_page.setData({
      address:address
    })

    prev_page.getOrderPrepare();

    //关闭当前页面
    wx.navigateBack({
      delta:1
    })

    /*
    wx.setStorageSync('addressInfo', address);
    wx.redirectTo({
      url: '/pages/order-create/order-create'
    })

    */
  },
  removeAddress:function(e){

    var me = this;
    var id = e.currentTarget.dataset.id;
    api.removeAddress({id:id} , function(response){
      console.log(response);

      if(response.status==1){
        me.getAddressList();
      }
    })

  },

  setDefaultAddress:function(e){
    //设置默认地址
    var me = this;
    var id = e.currentTarget.dataset.id;
    api.setDefaultAddress({id:id} , function(response){
      console.log(response);
      if(response.status==1){
        me.getAddressList();
      }
    })
  },
  editAddress:function(e){

    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/address/add?type=edit&id='+id,
    })

  },
  selectTab:function( e ){
    var index = e.currentTarget.dataset.index;

    this.setData({
      tab_index: index
    })
  },
  swiperChange: function (e) {
    console.log(e);
    var page = this;
    page.setData({
        tab_index: e.detail.current
    });
},
})